<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Share, DocumentCopy, Refresh, Switch } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 接口定义
interface ReferralProfile {
  id: string
  referralCode: string
  profileType: string
  isActive: boolean
  createdAt: string
  updatedAt: string
}

interface ReferralStats {
  totalReferrals: number
  activeReferrals: number
  thisMonthReferrals: number
}

// 响应式数据
const referralProfile = ref<ReferralProfile | null>(null)
const referralStats = ref<ReferralStats>({
  totalReferrals: 0,
  activeReferrals: 0,
  thisMonthReferrals: 0
})
const loading = ref(false)

// 页面加载时获取推荐码信息
onMounted(async () => {
  await loadReferralProfile()
  if (referralProfile.value) {
    await loadReferralStats()
  }
})

// 加载推荐码信息
const loadReferralProfile = async () => {
  try {
    const response = await request.get('/api/admin/admin-referral')
    if (response.data.profile) {
      referralProfile.value = response.data.profile
    }
  } catch (error: any) {
    if (error.response?.status !== 404) {
      ElMessage.error('추천코드 정보를 가져오는데 실패했습니다')
    }
  }
}

// 加载推荐统计
const loadReferralStats = async () => {
  try {
    const response = await request.get('/api/admin/admin-referral/stats')
    referralStats.value = response.data
  } catch (error) {
    console.error('추천 통계 로드 실패:', error)
    ElMessage.error('추천 통계를 가져오는데 실패했습니다')
  }
}

// 生成推荐码
const generateReferralCode = async () => {
  loading.value = true
  try {
    const response = await request.post('/api/admin/admin-referral')
    referralProfile.value = response.data.profile
    ElMessage.success('추천코드가 성공적으로 생성되었습니다')
    await loadReferralStats()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '추천코드 생성에 실패했습니다')
  } finally {
    loading.value = false
  }
}

// 切换状态
const toggleStatus = async () => {
  if (!referralProfile.value) return

  loading.value = true
  try {
    const newStatus = !referralProfile.value.isActive
    const response = await request.put('/api/admin/admin-referral', {
      isActive: newStatus
    })
    referralProfile.value = response.data.profile
    ElMessage.success(`추천코드가 ${newStatus ? '활성화' : '비활성화'}되었습니다`)
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '상태 변경에 실패했습니다')
  } finally {
    loading.value = false
  }
}

// 重新生成代码
const regenerateCode = async () => {
  try {
    await ElMessageBox.confirm(
      '새로운 추천코드를 생성하시겠습니까? 기존 코드는 더 이상 사용할 수 없습니다.',
      '확인',
      {
        confirmButtonText: '확인',
        cancelButtonText: '취소',
        type: 'warning',
      }
    )

    loading.value = true
    const response = await request.post('/api/admin/admin-referral/regenerate')
    referralProfile.value = response.data.profile
    ElMessage.success('새로운 추천코드가 생성되었습니다')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.error || '코드 재생성에 실패했습니다')
    }
  } finally {
    loading.value = false
  }
}

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('추천코드가 클립보드에 복사되었습니다')
  } catch (error) {
    ElMessage.error('복사에 실패했습니다')
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('ko-KR')
}
</script>

<template>
  <div class="admin-referral-view">
    <!-- 页面标题 -->
    <div class="page-header mobile-padding">
      <div class="header-content">
        <el-icon class="page-icon" size="24">
          <Share />
        </el-icon>
        <div class="header-text">
          <h1 class="page-title">관리자 추천코드</h1>
          <p class="page-subtitle">관리자 전용 추천코드를 생성하고 관리할 수 있습니다</p>
        </div>
      </div>
    </div>

    <div class="page-content">
      <!-- 没有推荐码的情况 -->
      <div v-if="!referralProfile" class="no-referral-section mobile-padding">
        <div class="mobile-card">
          <div class="mobile-card-title">
            <el-icon>
              <Share />
            </el-icon>
            추천코드 생성
          </div>
          <div class="card-content">
            <div class="empty-state">
              <el-icon size="64" color="#C0C4CC">
                <Share />
              </el-icon>
              <h3>추천코드가 없습니다</h3>
              <p>아직 관리자 추천코드가 생성되지 않았습니다.</p>
              <p>추천코드를 생성하면 사용자들이 이 코드를 사용하여 회원가입할 수 있습니다.</p>
            </div>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="generateReferralCode"
              style="width: 100%; margin-top: 20px;"
            >
              <el-icon><Share /></el-icon>
              {{ loading ? '생성 중...' : '추천코드 생성' }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 有推荐码的情况 -->
      <div v-else class="referral-section">
        <!-- 推荐码信息卡片 -->
        <div class="referral-info-section mobile-padding">
          <div class="mobile-card">
            <div class="mobile-card-title">
              <el-icon>
                <Share />
              </el-icon>
              관리자 추천코드
              <el-tag
                :type="referralProfile.isActive ? 'success' : 'info'"
                size="small"
                style="margin-left: auto;"
              >
                {{ referralProfile.isActive ? '활성' : '비활성' }}
              </el-tag>
            </div>

            <div class="referral-info">
              <!-- 推荐码显示 -->
              <div class="code-section">
                <div class="code-label">추천코드</div>
                <div class="code-display">
                  <span class="code-text">{{ referralProfile.referralCode }}</span>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="DocumentCopy"
                    @click="copyToClipboard(referralProfile.referralCode)"
                  >
                    복사
                  </el-button>
                </div>
              </div>

              <!-- 基本信息 -->
              <div class="info-grid">
                <div class="info-item">
                  <span class="info-label">생성일</span>
                  <span class="info-value">{{ formatDate(referralProfile.createdAt) }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">마지막 수정</span>
                  <span class="info-value">{{ formatDate(referralProfile.updatedAt) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="actions-section mobile-padding">
          <div class="mobile-card">
            <div class="mobile-card-title">
              <el-icon>
                <Switch />
              </el-icon>
              관리 작업
            </div>
            <div class="actions-grid">
              <el-button
                :type="referralProfile.isActive ? 'warning' : 'success'"
                :loading="loading"
                @click="toggleStatus"
                style="flex: 1;"
              >
                <el-icon><Switch /></el-icon>
                {{ referralProfile.isActive ? '비활성화' : '활성화' }}
              </el-button>
              <el-button
                type="info"
                :loading="loading"
                @click="regenerateCode"
                style="flex: 1;"
              >
                <el-icon><Refresh /></el-icon>
                새 코드 생성
              </el-button>
            </div>
          </div>
        </div>

        <!-- 추천 통계 -->
        <div class="stats-section mobile-padding">
          <div class="mobile-card">
            <div class="mobile-card-title">
              <el-icon>
                <Share />
              </el-icon>
              추천 통계
            </div>
            <div class="mobile-stats-grid" style="grid-template-columns: repeat(3, 1fr);">
              <div class="mobile-stats-card">
                <div class="mobile-stats-value">{{ referralStats.totalReferrals }}</div>
                <div class="mobile-stats-label">총 추천수</div>
              </div>
              <div class="mobile-stats-card">
                <div class="mobile-stats-value">{{ referralStats.activeReferrals }}</div>
                <div class="mobile-stats-label">활성 추천</div>
              </div>
              <div class="mobile-stats-card">
                <div class="mobile-stats-value">{{ referralStats.thisMonthReferrals }}</div>
                <div class="mobile-stats-label">이번 달</div>
              </div>
            </div>

            <!-- 统计数据提示 -->
            <div v-if="referralStats.totalReferrals === 0 && referralStats.activeReferrals === 0 && referralStats.thisMonthReferrals === 0"
                 class="stats-notice">
              <el-alert
                title="통계 데이터"
                description="추천 통계 데이터가 아직 없거나 로드 중입니다. 사용자가 추천코드를 사용하면 여기에 통계가 표시됩니다."
                type="info"
                :closable="false"
                show-icon
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.admin-referral-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-icon {
  color: var(--el-color-primary);
}

.header-text {
  flex: 1;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
  line-height: 1.4;
}

.page-content {
  flex: 1;
  overflow-y: auto;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-state h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 16px 0 8px 0;
}

.empty-state p {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 4px 0;
  line-height: 1.5;
}

/* 推荐码信息样式 */
.referral-info {
  padding: 16px 0;
}

.code-section {
  margin-bottom: 20px;
}

.code-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
}

.code-display {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
}

.code-text {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-color-primary);
  flex: 1;
  letter-spacing: 2px;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.info-value {
  font-size: 14px;
  color: var(--el-text-color-primary);
  font-weight: 500;
}

/* 操作按钮样式 */
.actions-grid {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

/* 统计提示样式 */
.stats-notice {
  margin-top: 16px;
}

/* 响应式调整 */
@media (max-width: 360px) {
  .code-display {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .actions-grid {
    flex-direction: column;
  }

  .actions-grid .el-button {
    flex: none !important;
  }
}
</style>
